package com.cxh.rmsq.ui.adapter.self

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.db.model.CommunityContent
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.ui.activity.self.CommentDetailActivity
import com.cxh.rmsq.ui.activity.self.LookUserDetailActivity2
import com.cxh.rmsq.ui.activity.self.PreViewImgOrVideoActivity
import com.cxh.rmsq.ui.activity.self.PublishCommunityActivity
import com.cxh.rmsq.ui.widget.SelectableRoundedImageView
import com.cxh.rmsq.utils.MyGridView
import com.cxh.rmsq.utils.MyUtils
import com.cxh.rmsq.utils.loadImage
import com.cxh.rmsq.utils.loadThumbnail
import com.cxh.rmsq.utils.loadVideoThumbnail
import com.hjq.shape.layout.ShapeRelativeLayout
import com.hjq.shape.view.ShapeImageView
import com.hjq.shape.view.ShapeTextView
import com.xuexiang.xui.widget.imageview.RadiusImageView
import io.rong.imkit.RongIM
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 *
 */
class CircleListAdapter(type: Int, private val listener: OnCustomClickListener) :
    BaseQuickAdapter<CommunityContent, BaseViewHolder>(R.layout.item_circle_list),
    LoadMoreModule {
    private val mListener: OnCustomClickListener

    init {
        addChildClickViewIds(R.id.iv_like)
        this.mListener = listener
    }

    var type = type
    private var mData = mutableListOf<String>() //图片

    override fun convert(holder: BaseViewHolder, item: CommunityContent) {
        with(holder) {

            getView<LinearLayout>(R.id.ll_comment).isVisible = 2 != type
            if (2 == type) {//草稿箱
                getView<LinearLayout>(R.id.ll_auth).isVisible = false
                getView<LinearLayout>(R.id.stv_top).isVisible = false
            } else {
                if (1 == type) {//1==我的已发布列表 显示置顶
                    getView<LinearLayout>(R.id.stv_top).isVisible = item.top == 1
                } else {
                    getView<LinearLayout>(R.id.stv_top).isVisible = false
                }
                if (item.userId.toString() == IMManager.getInstance().currentId) {//自己
                    if (item.auth == 2) {//
                        getView<LinearLayout>(R.id.ll_auth).isVisible = true
                        getView<ImageView>(R.id.iv_auth_img).setImageDrawable(
                            context.resources.getDrawable(
                                R.mipmap.icon_trend_order
                            )
                        )
                        getView<TextView>(R.id.tv_auth_name).text = "好友可见"
                    } else if (item.auth == 3) {//
                        getView<LinearLayout>(R.id.ll_auth).isVisible = true
                        getView<ImageView>(R.id.iv_auth_img).setImageDrawable(
                            context.resources.getDrawable(
                                R.mipmap.icon_trend_someone
                            )
                        )
                        getView<TextView>(R.id.tv_auth_name).text = "部分可见"
                    } else if (item.auth == 4) {//
                        getView<LinearLayout>(R.id.ll_auth).isVisible = true
                        getView<ImageView>(R.id.iv_auth_img).setImageDrawable(
                            context.resources.getDrawable(
                                R.mipmap.icon_trend_onlyself
                            )
                        )
                        getView<TextView>(R.id.tv_auth_name).text = "仅自己可见"
                    } else {
                        getView<LinearLayout>(R.id.ll_auth).isVisible = false
                    }
                } else {
                    getView<LinearLayout>(R.id.ll_auth).isVisible = false
                }
            }
            setText(R.id.tv_name, item.nickname)
            setText(R.id.tv_time, TimeUtils.getFriendlyTimeSpanByNow(item.createTime))
            if (!TextUtils.isEmpty(item.content)) {
                setText(R.id.tv_content, item.content)
                getView<TextView>(R.id.tv_content).isVisible = true
            } else {
                getView<TextView>(R.id.tv_content).isVisible = false
            }
            setText(R.id.tv_comment, item.commentCount.toString())
            setText(R.id.tv_like, item.likedCount.toString())
//            Log.e(
//                "ageeeeeee",
//                item.birthday!!.split("-")[0] + "+++" + item.birthday!!.split("-")[1] + "+++" + item.birthday!!.split(
//                    "-"
//                )[2].toInt()
//            )
            if (!TextUtils.isEmpty(item.birthday)) {
                setText(
                    R.id.tv_sex_age,
                    MyUtils.calculateAge2(
                        item.birthday!!.split("-")[0].toInt(),
                        item.birthday!!.split("-")[1].toInt(),
                        item.birthday!!.split("-")[2].toInt()
                    ).toString()
                )
            } else {
                setText(R.id.tv_sex_age, "0")
            }

            loadImage(item.avatar, holder.getView<SelectableRoundedImageView>(R.id.siv_header))
//            holder.getView<SelectableRoundedImageView>(R.id.siv_header).isOval = true
//            Glide.with(context)
//                .load(item.avatar)
//                .placeholder(R.mipmap.image_zanwei)
//                .into(holder.getView<SelectableRoundedImageView>(R.id.siv_header))

            if (1 == item.sex) {
                holder.getView<TextView>(R.id.tv_sex_age).setCompoundDrawablesWithIntrinsicBounds(
                    context.getResources().getDrawable(R.mipmap.icon_male),
                    null,
                    null,
                    null
                )
                holder.getView<TextView>(R.id.tv_sex_age)
                    .setBackgroundResource(R.drawable.shape_sex_male_bg)
            } else {
                holder.getView<TextView>(R.id.tv_sex_age).setCompoundDrawablesWithIntrinsicBounds(
                    context.getResources().getDrawable(R.mipmap.icon_male),
                    null,
                    null,
                    null
                )
                holder.getView<TextView>(R.id.tv_sex_age)
                    .setBackgroundResource(R.drawable.shape_sex_female_bg)
            }

            if (!TextUtils.isEmpty(item.isLiked.toString()) && item.isLiked == 1) {
                holder.getView<ImageView>(R.id.iv_like)
                    .setImageDrawable(context.resources.getDrawable(R.mipmap.icon_cicrle_liked))
            } else {
                holder.getView<ImageView>(R.id.iv_like)
                    .setImageDrawable(context.resources.getDrawable(R.mipmap.icon_cicrle_no_like))
            }

            if (item.vipLevel == 0) {//不是会员
                holder.getView<ImageView>(R.id.sll_vip).isVisible = false
            } else {
                holder.getView<ImageView>(R.id.sll_vip).isVisible = true
            }
            if (!TextUtils.isEmpty(item.groupsName)) {
                holder.getView<ShapeTextView>(R.id.stv_group_name).isVisible = true
                setText(R.id.stv_group_name, item.groupsName + " >")
                holder.getView<ShapeTextView>(R.id.stv_group_name).setOnClickListener {
//                    RongIM.getInstance()
//                        .startGroupChat(context, item.groupId.toString(), item.groupsName)
                    //申请加群
                    if (listener != null) {
                        listener.onGroupClick(holder.layoutPosition, item)
                    }
                }
            } else {
                holder.getView<ShapeTextView>(R.id.stv_group_name).isVisible = false
            }

            if (!TextUtils.isEmpty(item.circleName)) {
                holder.getView<ShapeTextView>(R.id.sll_circle).isVisible = true
                setText(R.id.stv_circle, item.circleName)
            } else {
                holder.getView<ShapeTextView>(R.id.sll_circle).isVisible = false
            }

            if (item.fileType == 1) {//图片
                if (!TextUtils.isEmpty(item.files)) {
                    if (item.files!!.contains(",")) {//多张
                        mData.clear()
                        holder.getView<MyGridView>(R.id.recyclerView).isVisible = true
                        holder.getView<ShapeImageView>(R.id.siv_signle_img).isVisible = false
                        holder.getView<ImageView>(R.id.iv_play).isVisible = false

                        var mAdapter = PicAdapter()
                        holder.getView<MyGridView>(R.id.recyclerView).adapter = mAdapter
                        mData.addAll(MyUtils.toList(item.files))
                        mAdapter.setData()
                        for (j in 0 until mData.size) {

                        }
                        holder.getView<MyGridView>(R.id.recyclerView)
                            .setOnItemClickListener { parent, view, position, id ->
                                Log.i("posi", "${position} ** ${parent.childCount - 1}")
                                if (listener != null) {
                                    listener.onItemClick(position, item)
                                }
//                                context.startActivity(
//                                    Intent(context, PreViewImgOrVideoActivity::class.java)
//                                        .putExtra("type", item.fileType)
//                                        .putExtra("url", item.files)
//                                )
                            }
                        holder.getView<MyGridView>(R.id.recyclerView)
                            .setOnItemLongClickListener { adapterView, view, i, l ->
                                if (listener != null) {
                                    listener.onItemLongClick(i, item)
                                }
                                return@setOnItemLongClickListener true
                            }
                    } else {
                        holder.getView<MyGridView>(R.id.recyclerView).isVisible = false
                        holder.getView<ShapeImageView>(R.id.siv_signle_img).isVisible = true
                        holder.getView<ImageView>(R.id.iv_play).isVisible = false

                        loadImage(item.files, holder.getView<ShapeImageView>(R.id.siv_signle_img))
//                        Glide.with(context)
//                            .load(item.files)
//                            .placeholder(R.mipmap.image_zanwei)
//                            .diskCacheStrategy(DiskCacheStrategy.ALL)
//                            .into(holder.getView<ShapeImageView>(R.id.siv_signle_img))
                        holder.getView<ShapeImageView>(R.id.siv_signle_img).setOnClickListener {
                            if (listener != null) {
                                listener.onItemClick(holder.layoutPosition, item)
                            }
//                            context.startActivity(
//                                Intent(context, PreViewImgOrVideoActivity::class.java)
//                                    .putExtra("type", item.fileType)
//                                    .putExtra("url", item.files)
//                            )
                        }
                        holder.getView<ShapeImageView>(R.id.siv_signle_img).setOnLongClickListener {
                            if (listener != null) {
                                listener.onItemLongClick(holder.layoutPosition, item)
                            }
                            return@setOnLongClickListener true
                        }
                    }

                }
            } else if (item.fileType == 2) {//视频
                holder.getView<MyGridView>(R.id.recyclerView).isVisible = false
                holder.getView<ShapeImageView>(R.id.siv_signle_img).isVisible = true
                holder.getView<ImageView>(R.id.iv_play).isVisible = true

                loadVideoThumbnail(
                    context,
                    item.files.toString(),
                    holder.getView<ShapeImageView>(R.id.siv_signle_img)
                )

                CoroutineScope(Dispatchers.Main).launch {
                    val bitmap = loadThumbnail(
                        context = itemView.context,
                        videoUri = item.files.toString(),
                        width = 800,
                        height = 600,
                        imageView = holder.getView<ShapeImageView>(R.id.siv_signle_img)
                    )

//                    Glide.with(context)
//                        .asBitmap()
//                        .load(bitmap)
//                        .override(800, 600) // 可选：指定目标尺寸
//                        .centerCrop()
//                        .into(holder.getView<ShapeImageView>(R.id.siv_signle_img))
//                    holder.getView<ShapeImageView>(R.id.siv_signle_img).setImageBitmap(bitmap)
                }

                holder.getView<ShapeImageView>(R.id.siv_signle_img).setOnClickListener {
//                    if (listener != null) {
//                        listener.onItemClick(holder.layoutPosition, item)
//                    }
                    context.startActivity(
                        Intent(context, PreViewImgOrVideoActivity::class.java)
                            .putExtra("type", item.fileType)
                            .putExtra("url", item.files)
                    )
                }
                holder.getView<ShapeImageView>(R.id.siv_signle_img).setOnLongClickListener {
                    if (listener != null) {
                        listener.onItemLongClick(holder.layoutPosition, item)
                    }
                    return@setOnLongClickListener true
                }
            } else {
                holder.getView<MyGridView>(R.id.recyclerView).isVisible = false
                holder.getView<ShapeImageView>(R.id.siv_signle_img).isVisible = false
                holder.getView<ImageView>(R.id.iv_play).isVisible = false

            }

            holder.getView<ShapeRelativeLayout>(R.id.sll).setOnClickListener {
                val intent = Intent(context, LookUserDetailActivity2::class.java)
                intent.putExtra(IntentExtra.STR_TARGET_ID, item.userId.toString())
                intent.putExtra("isContact", "1")
                context.startActivity(intent)
            }
            holder.itemView.setOnClickListener {
                if (2 == type) {//草稿箱
                    val intent = Intent(context, PublishCommunityActivity::class.java)
                    intent.putExtra("id", item.id.toString())
                    context.startActivity(intent)
                } else {
                    val intent = Intent(context, CommentDetailActivity::class.java)
                    intent.putExtra("id", item.id.toString())
//                intent.putExtra("isMine", "2")
                    context.startActivity(intent)
                }
            }
        }
    }

    override fun getItemId(position: Int): Long {
        return super.getItemId(position)
    }

    interface OnCustomClickListener {
        fun onItemClick(position: Int, data: CommunityContent?) // 根据需求定义参数
        fun onGroupClick(position: Int, data: CommunityContent?) // 根据需求定义参数
        fun onItemLongClick(position: Int, data: CommunityContent?) // 根据需求定义参数
    }

    inner class PicAdapter : BaseAdapter() {
        private var mUris: List<Uri>? = null
        private var mPaths: List<String>? = null
        fun setData(uris: List<Uri>?, paths: List<String>?) {
            mUris = uris
            mPaths = paths
            notifyDataSetChanged()
        }

        fun setData() {
            notifyDataSetChanged()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val view: View?
            val viewHolder: ViewHolder

            if (convertView == null) {
                val inflater =
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                // 需要创建视图 animals_list
                view = inflater.inflate(R.layout.item_grid_picture, null)
                viewHolder = ViewHolder(view)
                view?.tag = viewHolder
            } else {
                view = convertView
                viewHolder = view.tag as ViewHolder
            }
            viewHolder.deleteImg!!.visibility = View.GONE
            // 先重置为占位图
            viewHolder.imgUrl!!.setImageResource(R.mipmap.image_zanwei);
            loadImage(mData[position], viewHolder.imgUrl!!)

//            viewHolder.imgUrl!!.setOnClickListener {
            //这里可以添加查看大图的逻辑
            /*Intent intent = new Intent(parent.getContext(), FriendCircleReleaseActivity.class);
            intent.putExtra("position", position);
            intent.putStringArrayListExtra("urlList", mData);
            startActivity(intent);*/
//            }


            return view as View
        }

        override fun getItem(position: Int): Any {
            return mData.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return if (mData == null) 0 else mData.size

        }

        private inner class ViewHolder(view: View?) {
            var imgUrl: RadiusImageView? = null
            var deleteImg: ImageView? = null

            init {
                this.imgUrl = view?.findViewById(R.id.img_url)
                this.deleteImg = view?.findViewById(R.id.delete_picture)
            }
        }
    }
}